import {
  Form,
  Button,
  DatePicker,
  Radio,
  Select,
  Steps,
  Input,
  Row,
  Col,
  Select,
  InputNumber,
  Table,
  message,
} from 'antd';
import React, {Component} from 'react';
import {FormComponentProps} from 'antd/es/form';
import {TableListItem} from '../data.d';

const FormItem = Form.Item;
const {Step} = Steps;
const {TextArea} = Input;
const {Option} = Select;
const RadioGroup = Radio.Group;
import validator from '@/utils/Validator';
import BizParams from '../utils/BizParams.tsx';
import CurrencySelect from '../utils/CurrencySelect.tsx';
import PortSelect from '../utils/PortSelect.tsx';
import {connect} from 'dva';
import ChooseProduct from './ChooseProduct.tsx';

const R = require('ramda');

export interface FormValsType extends Partial<TableListItem> {
  target?: string;
  template?: string;
  type?: string;
  time?: string;
  frequency?: string;
}

export interface UpdateFormProps extends FormComponentProps {
  handleUpdateModalVisible: (flag?: boolean, formVals?: FormValsType) => void;
  handleModalVisible: (values: FormValsType) => void;
  updateModalVisible: boolean;
  values: Partial<TableListItem>;
}

export interface UpdateFormState {
  formVals: FormValsType;
}

const orderForm = Form.create()(class OrderForm extends React.Component {
    static defaultProps = {
      handleModalVisible: () => {
      },
      handleUpdateModalVisible: () => {
      },
      values: {},
    };

    constructor(props: UpdateFormProps) {
      super(props);
      this.state = {
        showFreight: false,
        showPremium: false,
        retrodictFlag: false, //倒推增加一个刷新价格按钮，避免过多事件的监听，点下一步之前必须保证为false
        retrodictRate: true, //true：倒推 false: 正推
        productList: [],
        productflag: false, //产品列表数据标记
        priceClauseflag: true, //价格条款标记
        decTypeflag: true,  //报关方式标记
        cstDecTypeflag: true, //客户报关方式附加信息标记
        transportflag: true, //运输方式附加信息标记
      };
    }

    statistics = {};

    handleResetFields = () => {
      this.props.form.resetFields();
      this.setState({retrodictFlag: false});
      const {dispatch, handleModalVisible, handleSearch} = this.props;
      dispatch({
        type: 'orderAgent/refreshState',
        payload: {
          order: {},
          orderTgApproval: {},
          orderProductDetails: [],
        },
      });
      handleModalVisible(false);
      handleSearch();
    };

    handleChangeContractType = value => {
      const {
        dispatch,
        form: {setFieldsValue},
      } = this.props;
      if (value === '1') {
        //系统生成的话，要清空手输的协议号
        setFieldsValue({contractno: ''});
      }

      dispatch({type: 'orderAgent/refreshState', payload: {order: {contracttype: value}}});
    };

    handleChangeDeclarationType = value => {
      this.setState({decTypeflag: false, cstDecTypeflag: false, transportflag: false});

      if (value === '1') {
        //综服企业报关，清理客户报关
        this.props.form.setFieldsValue({
          cstdeclarationtype: '',
          cstdeclarationcode: '',
          cstreceiver: '',
          cstrectelephone: '',
          cstdeclarationaddress: '',
        }); //清理数据
        this.setState({showEmailType: false, showNoPaperType: false, showMemo: false}); //隐藏元素
        //显示综服报关元素
        if (this.props.form.getFieldValue('portoftransport') === '1') {
          //海运
          this.setState({showSeaTrans: true});
        } else if (this.props.form.getFieldValue('portoftransport') === '2') {
          //陆运
          this.setState({showRoadTrans: true});
        } else if (this.props.form.getFieldValue('portoftransport') === '3') {
          //空运
          this.setState({showAirTrans: true});
        }
      } else if (value === '2') {
        this.props.form.setFieldsValue({
          totalvolume: '',
          carmodel: '',
          weightSea: '',
          weightRoad: '',
          plateno: '',
          mainfestno: '',
          tonnage: '',
          containertype: '',
          containerno: '',
          enchasetype: '',
          size20: '',
          size40: '',
          size45: '',
          sizeother: '',
          boxno: '',
          memo: '',
        }); //清理数据
        this.setState({
          showSeaFCL: false,
          showSeaLCL: false,
          showRoadTrans: false,
          showRoadTOC: false,
          showRoadCC: false,
          showAirTrans: false,
          showMemo: true,
          showSeaTrans: false,
        }); //隐藏元素
      }
    };

    handleChangePortOfTransport = value => {
      this.setState({transportflag: false});

      //如果是综服企业报关 才执行清理跟显隐的逻辑
      if (this.props.form.getFieldValue('declarationtype') === '1') {
        if (value === '1') {
          //海运
          this.props.form.setFieldsValue({
            totalvolume: '',
            carmodel: '',
            plateno: '',
            mainfestno: '',
            tonnage: '',
            containertype: '',
            containerno: '',
          }); //清理数据
          this.setState({
            showRoadTrans: false,
            showRoadTOC: false,
            showRoadCC: false,
            showAirTrans: false,
            showSeaTrans: true,
          }); //隐藏元素
        } else if (value === '2') {
          //陆运
          this.props.form.setFieldsValue({
            totalvolume: '',
            enchasetype: '',
            size20: '',
            size40: '',
            size45: '',
            sizeother: '',
            boxno: '',
          }); //清理数据
          this.setState({
            showSeaTrans: false,
            showSeaFCL: false,
            showSeaLCL: false,
            showAirTrans: false,
            showRoadTrans: true,
          }); //隐藏元素
        } else if (value === '3') {
          //空运
          this.props.form.setFieldsValue({
            carmodel: '',
            weightSea: '',
            weightRoad: '',
            plateno: '',
            mainfestno: '',
            tonnage: '',
            containertype: '',
            containerno: '',
            enchasetype: '',
            size20: '',
            size40: '',
            size45: '',
            sizeother: '',
            boxno: '',
          }); //清理数据
          this.setState({
            showSeaTrans: false,
            showSeaFCL: false,
            showSeaLCL: false,
            showRoadTrans: false,
            showRoadTOC: false,
            showRoadCC: false,
            showAirTrans: true,
          }); //隐藏元素
        }
      }
    };

    handleChangeCstDeclarationType = value => {
      this.setState({cstDecTypeflag: false});

      if (value === '1') {
        //快递寄资料
        //清理无纸化报关
        this.props.form.setFieldsValue({cstdeclarationcode: ''}); //清理数据
        this.setState({showNoPaperType: false, showEmailType: true}); //隐藏元素
      } else if (value === '2') {
        //无纸化
        //清理快递寄资料
        this.props.form.setFieldsValue({
          cstreceiver: '',
          cstrectelephone: '',
          cstdeclarationaddress: '',
        }); //清理数据
        this.setState({showEmailType: false, showNoPaperType: true}); //隐藏元素
      }
    };

    handleChangeDrawerType = value => {
      const {orderProductDetails} = this.props;
      let productList = [];
      if (!this.state.productflag) {
        productList = orderProductDetails;
        this.setState({productflag: true});
      } else {
        productList = R.clone(this.state.productList);
      }

      this.setState({retrodictRate: value === '2'});
      if (value === '1') {
        //正推的话要清空掉倒推汇率
        this.props.form.setFieldsValue({retrodictrate: 0, retrodictfee: 0});
        //清空产品列表的倒推费用跟开票金额
        R.map(row => {
          row.retrodictcost = 0;
          row.draweramount = 0;
        }, productList);
        this.setState({productList: productList, retrodictFlag: false});
      }
    };

    handleRefreshAmt = () => {
      const {
        userInfo,
        orderProductDetails,
        form: {getFieldValue},
      } = this.props;

      let productList = [];
      if (!this.state.productflag) {
        productList = orderProductDetails;
        this.setState({productflag: true});
      } else {
        productList = R.clone(this.state.productList);
      }

      //取倒推汇率
      let retrodictrate = getFieldValue('retrodictrate');
      if (!retrodictrate || retrodictrate < 0) {
        message.error('倒推汇率不能空，且必须大于0');
        return;
      }

      let agencyfee = R.isNil(userInfo.agencyfee) ? 0 : userInfo.agencyfee / 100;//费率
      if (retrodictrate === agencyfee) {
        message.error('汇率不能等于代理费率,请重新输入');
        return;
      }
      //取倒推费用
      let retrodictfee = getFieldValue('retrodictfee');
      //先循环一次产品，累加开票金额，按比例均摊倒推费用
      let totalDrawerAmt = 0;
      let checkDrawerAmtFlag = false;
      productList.map(item => {
        if (!item.draweramount || retrodictrate < 0) checkDrawerAmtFlag = true;
        else totalDrawerAmt = totalDrawerAmt + item.draweramount;
      });
      if (checkDrawerAmtFlag) {
        message.error('请先录入所有产品倒推的开票金额，金额不为小于0');
        return;
      }
      //再一次循环计算产品单价，倒推费用
      productList.map(item => {
        let productnumber = item.productnumber ? item.productnumber : 1; //数量没有输入则先默认为1
        item.retrodictcost =
          Math.round(((item.draweramount * retrodictfee) / totalDrawerAmt) * 100) / 100; //均摊倒推费用，保留两位小数
        item.productprice = (
          ((item.draweramount * (1 + item.zzrate / 100 - item.taxrate / 100)) /
            (1 + item.zzrate / 100) +
            item.retrodictcost) /
          (retrodictrate - agencyfee) /
          productnumber
        ).toFixed(4); //计算单价
        item.totalprice = Math.round(item.productprice * productnumber * 100) / 100; //计算产品总价
      });
      this.setState({productList, retrodictFlag: false});
    };

    triggleRefreshAmt = () => {
      this.setState({retrodictFlag: true});
    };

    handleChangePriceClause = value => {
      this.setState({priceClauseflag: false});

      if (value === '1') {
        this.setState({showPremium: true});
        this.setState({showFreight: true});
      }
      if (value === '2') {
        this.props.form.setFieldsValue({premium: 0, premiumcurrency: ''});
        this.setState({showPremium: false});
        this.setState({showFreight: true});
      }
      if (value === '4') {
        this.props.form.setFieldsValue({freight: 0, freightcurrency: ''});
        this.setState({showPremium: true});
        this.setState({showFreight: false});
      }
      if (value !== '1' && value !== '2' && value !== '4') {
        //不是CIF，先清理保费
        this.props.form.setFieldsValue({freight: 0, freightcurrency: ''});
        //不是C&F，再清理运费
        this.props.form.setFieldsValue({premium: 0, premiumcurrency: ''});
        this.setState({showFreight: false});
        this.setState({showPremium: false});
      }
    };

    handleOpenAddProduct = () => {
      const {dispatch, userInfo, orderProductDetails} = this.props;
      dispatch({
        type: 'orderAgent/queryProductList',
        payload: {
          cstId: userInfo.id,
          page: 1,
          size: 10,
        },
      });
      if (!this.state.productflag) {
        this.setState({productList: orderProductDetails, productflag: true});
      }
      this.formRef.handleOpen();
    };

    handleChangeProductNumber = (record, value) => {
      const {userInfo, orderProductDetails, form: {getFieldValue}} = this.props;
      let productList = [];
      if (!this.state.productflag) {
        productList = orderProductDetails;
        this.setState({productflag: true});
      } else {
        productList = R.clone(this.state.productList);
      }

      let agencyfee = R.isNil(userInfo.agencyfee) ? 0 : userInfo.agencyfee / 100;//费率
      let retrodictRate = R.isNil(getFieldValue('retrodictrate')) ? 0 : getFieldValue('retrodictrate');
      R.map(row => {
        if (row.id === record.id) {
          row.productnumber = value;
          row.productweight = Math.round(value * row.singleweight * 10000) / 10000;
          if (this.state.retrodictRate && retrodictRate !== agencyfee) {
            //倒推 数量联动单价
            let draweramount =
              R.isNil(row.draweramount) || R.isEmpty(row.draweramount) ? 0 : row.draweramount; //倒推开票金额默认为0
            let retrodictcost =
              R.isNil(row.retrodictcost) || R.isEmpty(row.retrodictcost) ? 0 : row.retrodictcost; //倒推费用默认为0
            let productnumber =
              R.isNil(row.productnumber) || R.isEmpty(row.productnumber) ? 1 : row.productnumber; //数量默认为1
            row.productprice = (
              ((draweramount * (1 + row.zzrate / 100 - row.taxrate / 100)) / (1 + row.zzrate / 100) +
                retrodictcost) /
              (retrodictRate - agencyfee) /
              productnumber
            ).toFixed(4);
          }
          row.totalprice = Math.round(row.productprice * row.productnumber * 100) / 100;
        }
      }, productList);
      this.setState({productList: productList});
    };

    handleChangePackageNumber = (record, value) => {
      const {orderProductDetails} = this.props;
      let productList = [];
      if (!this.state.productflag) {
        productList = orderProductDetails;
        this.setState({productflag: true});
      } else {
        productList = R.clone(this.state.productList);
      }

      R.map(row => {
        if (row.id === record.id) {
          row.packagenumber = value;
        }
      }, productList);
      this.setState({productList: productList});
    };

    handleChangeProductPrice = (record, value) => {
      const {orderProductDetails} = this.props;
      let productList = [];
      if (!this.state.productflag) {
        productList = orderProductDetails;
        this.setState({productflag: true});
      } else {
        productList = R.clone(this.state.productList);
      }

      R.map(row => {
        if (row.id === record.id) {
          row.productprice = value;
          row.totalprice = Math.round(value * row.productnumber * 100) / 100;
        }
      }, productList);
      this.setState({productList: productList});
    };

    handleChangeProductWeight = (record, value) => {
      const {orderProductDetails} = this.props;
      let productList = [];
      if (!this.state.productflag) {
        productList = orderProductDetails;
        this.setState({productflag: true});
      } else {
        productList = R.clone(this.state.productList);
      }

      R.map(row => {
        if (row.id === record.id) {
          row.productweight = value;
        }
      }, productList);
      this.setState({productList: productList});
    };

    handleChangeGrossWeight = (record, value) => {
      const {orderProductDetails} = this.props;
      let productList = [];
      if (!this.state.productflag) {
        productList = orderProductDetails;
        this.setState({productflag: true});
      } else {
        productList = R.clone(this.state.productList);
      }

      R.map(row => {
        if (row.id === record.id) {
          row.grossweight = value;
        }
      }, productList);
      this.setState({productList: productList});
    };

    drawerMap = {};
    handleChangeDrawer = (record, value) => {
      const {orderProductDetails} = this.props;
      let productList = [];
      if (!this.state.productflag) {
        productList = orderProductDetails;
        this.setState({productflag: true});
      } else {
        productList = R.clone(this.state.productList);
      }

      R.map(row => {
        if (row.id === record.id) {
          row.drawerid = value;
          row.drawername = this.drawerMap[value];
        }
      }, productList);
      this.setState({productList: productList});
    };

    handleChangeDrawerAmount = (record, value) => {
      const {orderProductDetails} = this.props;
      let productList = [];
      if (!this.state.productflag) {
        productList = orderProductDetails;
        this.setState({productflag: true});
      } else {
        productList = R.clone(this.state.productList);
      }

      productList.map(item => {
        if (item.id === record.id) item.draweramount = value;
      });
      this.setState({retrodictFlag: true});
    };

    handleChangeProductSize = (record, e) => {
      const {orderProductDetails} = this.props;
      let productList = [];
      if (!this.state.productflag) {
        productList = orderProductDetails;
        this.setState({productflag: true});
      } else {
        productList = R.clone(this.state.productList);
      }

      R.map(row => {
        if (row.id === record.id) {
          row.productsize = e.target.value;
        }
      }, productList);
      this.setState({productList: productList});
    };

    handleDeleteProduct = record => {
      const {orderProductDetails} = this.props;

      let productList = [];
      if (!this.state.productflag) {
        productList = R.difference(orderProductDetails, [record]);
        this.setState({productflag: true});
      } else {
        productList = R.difference(this.state.productList, [record]);
      }

      this.setState({productList: productList, retrodictFlag: true});
    };

    handleInitColumns = (disabled) => {
      return R.without(
        [null],
        [
          {title: '品名', dataIndex: 'productname', key: 'productname'},
          {title: '型号', dataIndex: 'productmodel', key: 'productmodel'},
          {title: '品牌类型', dataIndex: 'productbranchname', key: 'productbranchname'},
          {title: '品牌', dataIndex: 'productbranch', key: 'productbranch'},
          {title: '币种', dataIndex: 'productcurrency', key: 'productcurrency'},
          {
            title: '数量',
            dataIndex: 'productnumber',
            key: 'productnumber',
            render: (text, record, index) => {
              return (
                <InputNumber disabled={disabled}
                             min={0}
                             max={99999999999999}
                             value={record.productnumber}
                             onChange={this.handleChangeProductNumber.bind(this, record)}
                />
              );
            },
          },
          {title: '单位', dataIndex: 'productunit', key: 'productunit'},
          {
            title: '包装件数',
            dataIndex: 'packagenumber',
            key: 'packagenumber',
            render: (text, record, index) => {
              return (
                <InputNumber disabled={disabled}
                             min={0}
                             max={99999999999999}
                             value={record.packagenumber}
                             onChange={this.handleChangePackageNumber.bind(this, record)}
                />
              );
            },
          },
          {
            title: '单价',
            dataIndex: 'productprice',
            key: 'productprice',
            render: (text, record, index) => {
              return (
                <InputNumber disabled={disabled}
                             min={0}
                             max={99999999999999}
                             value={record.productprice}
                             onChange={this.handleChangeProductPrice.bind(this, record)}
                />
              );
            },
          },
          this.state.retrodictRate
            ? {
              title: '倒推开票金额(人民币)',
              dataIndex: 'draweramount',
              key: 'draweramount',
              render: (text, record, index) => {
                return (
                  <InputNumber disabled={disabled}
                               min={0}
                               max={99999999999999}
                               value={record.draweramount}
                               onChange={this.handleChangeDrawerAmount.bind(this, record)}
                  />
                );
              },
            }
            : null,
          {title: '单净重(Kg)', dataIndex: 'singleweight', key: 'singleweight'},
          {
            title: '净重(Kg)',
            dataIndex: 'productweight',
            key: 'productweight',
            render: (text, record, index) => {
              return (
                <InputNumber disabled={disabled}
                             min={0}
                             max={99999999999999}
                             value={record.productweight}
                             onChange={this.handleChangeProductWeight.bind(this, record)}
                />
              );
            },
          },
          {
            title: '毛重(Kg)',
            dataIndex: 'grossweight',
            key: 'grossweight',
            render: (text, record, index) => {
              return (
                <InputNumber disabled={disabled}
                             min={0}
                             max={99999999999999}
                             value={record.grossweight}
                             onChange={this.handleChangeGrossWeight.bind(this, record)}
                />
              );
            },
          },
          {
            title: '关联开票人',
            dataIndex: 'drawername',
            key: 'drawername',
            render: (text, record, index) => {
              return (
                <Select disabled={disabled}
                        style={{width: '100%'}}
                        value={record.drawerid + ''}
                        onChange={this.handleChangeDrawer.bind(this, record)}
                >
                  {!R.isNil(this.props.drawersList)
                    ? this.props.drawersList.map(item => {
                      if (!R.contains(item.id)(this.drawerMap)) this.drawerMap[item.id] = item.name;
                      return (
                        <Select.Option value={item.id + ''} key={item.id + ''}>
                          {item.name}: {item.taxplayercode}
                        </Select.Option>
                      );
                    })
                    : ''}
                </Select>
              );
            },
          },
          {title: '货值', dataIndex: 'totalprice', key: 'totalprice'},
          {
            title: '规格',
            dataIndex: 'productsize',
            key: 'productsize',
            render: (text, record, index) => {
              return (
                <Input disabled={disabled}
                       maxLength="1000"
                       style={{width: 'auto'}}
                       value={R.isNil(record.productsize) ? '' : record.productsize}
                       onChange={this.handleChangeProductSize.bind(this, record)}
                />
              );
            },
          },
          {title: '申报参数', dataIndex: 'productdeclarelements', key: 'productdeclarelements'},
          {title: '退税率', dataIndex: 'taxrate', key: 'taxrate'},
          {title: '增值税率', dataIndex: 'zzrate', key: 'zzrate'},
          {
            title: '操作',
            key: 'operation',
            render: (text, record, index) => {
              return (
                <div>
                  <a href="#" disabled={disabled} onClick={this.handleDeleteProduct.bind(this, record)}>
                    删除
                  </a>
                </div>
              );
            },
          },
        ],
      );
    };

    getForm = () => {
      const {form: {validateFields, getFieldValue}, dispatch, userInfo, recordFormValues, orderProductDetails} = this.props;
      validateFields((err, fieldsValue) => {
        if (err) return;
        let flag = true;

        let productList = [];
        if (!this.state.productflag) {
          productList = orderProductDetails;
        } else {
          productList = R.clone(this.state.productList);
        }

        let currency = fieldsValue.currencytype ? fieldsValue.currencytype : null;
        if (R.isEmpty(productList)) {
          message.error('请至少选择一个产品!');
          flag = false;
          return;
        }

        let agencyfee = R.isNil(userInfo.agencyfee) ? 0 : userInfo.agencyfee / 100;//费率
        if (
          this.state.retrodictRate &&
          getFieldValue('retrodictrate') === agencyfee
        ) {
          message.error('倒推汇率不能等于代理费率,请重新输入');
          flag = false;
          return;
        }
        if (this.state.retrodictRate && this.state.retrodictFlag) {
          message.error('数据有变，请先点击刷新价格');
          flag = false;
          return;
        }

        let totalpacknum = 0;
        R.map(row => {
          if (row.productcurrency !== currency) {
            message.error('所选产品币种必须与报关币种保持一致，请重新选择!');
            flag = false;
            return;
          }

          if (
            R.isNil(row.productnumber) ||
            R.isNil(row.packagenumber) ||
            R.isNil(row.productweight) ||
            R.isNil(row.grossweight) ||
            R.isNil(row.productprice)
          ) {
            message.error('产品：(' + row.productname + ') 信息不全，除规格外其他为必填项，请补全!');
            flag = false;
            return;
          }

          if (!row.drawerid) {
            message.error('请选择产品：(' + row.productname + ') 的开票人!');
            flag = false;
            return;
          }

          if (row.grossweight < row.productweight) {
            message.error('产品：(' + row.productname + ') 毛重不能小于净重');
            flag = false;
            return;
          }
          totalpacknum = totalpacknum + (R.isNil(row.packagenumber) ? 0 : row.packagenumber); //总包装件数
        }, productList);

        if (flag) {
          let dataSource = {...fieldsValue, ...this.statistics};
          dataSource.orderProductDetails = productList;
          dataSource.cstid = userInfo.id;

          let fun = '';
          if (recordFormValues.id) {
            fun = 'orderAgent/updateOrder';
            dataSource.id = recordFormValues.id;
          } else {
            fun = 'orderAgent/createOrder';
          }

          dispatch({
            type: fun,
            payload: {
              dataSource,
              onSuccess: () => {
                this.handleResetFields();
              },
              onFail: () => {
                this.handleResetFields();
              },
            },
          });
        }
      });
    };

    handleAddProducts = tempProductList => {
      this.setState({productList: R.concat(this.state.productList, tempProductList)});
    };

    render() {
      const {
        form: {getFieldDecorator, getFieldValue},
        userInfo,
        order,
        orderTgApproval,
        orderProductDetails,
        buyerList,
        supplygoodList,
        recordFormValues,
      } = this.props;

      let disabled = ['2', '4', '5', '6', '7'].includes(recordFormValues.status);
      let columns = this.handleInitColumns(disabled);

      let currency = '';
      let [totalnum, totalweight, totalgross, totleamount, totalpacknum] = [0, 0, 0, 0, 0];
      let productTotal = this.state.productflag ? this.state.productList : orderProductDetails;

      productTotal ? R.map(product => {
        currency = product.productcurrency;
        totalnum = totalnum + (R.isNil(product.productnumber) ? 0 : product.productnumber); //总数量
        totalweight = totalweight + (R.isNil(product.productweight) ? 0 : product.productweight); //总净重
        totalgross = totalgross + (R.isNil(product.grossweight) ? 0 : product.grossweight); //总毛重
        totleamount = totleamount + (R.isNil(product.totalprice) ? 0 : product.totalprice); //总货值
        totalpacknum = totalpacknum + (R.isNil(product.packagenumber) ? 0 : product.packagenumber); //总包装件数
      }, productTotal) : '';
      totalnum = Math.round(totalnum * 10000) / 10000;
      totalweight = Math.round(totalweight * 10000) / 10000;
      totalgross = Math.round(totalgross * 10000) / 10000;
      totleamount = Math.round(totleamount * 100) / 100; //两位小数 总价只保留两位小数
      totalpacknum = Math.round(totalpacknum * 10000) / 10000;
      this.statistics.totalnum = totalnum;
      this.statistics.totalweight = totalweight;
      this.statistics.totalgross = totalgross;
      this.statistics.totleamount = totleamount;
      this.statistics.totalpacknum = totalpacknum;

      let freightView = this.state.priceClauseflag
        ? ['1', '2'].includes(order.priceclause)
        : this.state.showFreight;
      let premiumView = this.state.priceClauseflag
        ? ['1', '4'].includes(order.priceclause)
        : this.state.showPremium;

      let cstDecView = this.state.decTypeflag
        ? order.declarationtype === '2'
        : this.state.showMemo;
      let cstDecOneView = this.state.cstDecTypeflag
        ? order.declarationtype === '2' && order.cstdeclarationtype === '2'
        : this.state.showNoPaperType;
      let cstDecTwoView = this.state.cstDecTypeflag
        ? order.declarationtype === '2' && order.cstdeclarationtype === '1'
        : this.state.showEmailType;


      return (
        <div>
          <Form style={{marginTop: 8}}>
            <Row gutter={24}>
              <Col span={6}>
                <FormItem label={<span>协议号生成方式</span>}>
                  {getFieldDecorator('contracttype', {
                    rules: [{required: true, message: '请选择协议号生成方式！'}],
                    initialValue: order.contracttype,
                  })(
                    <BizParams disabled={disabled}
                               sprCode="contractType"
                               onChange={this.handleChangeContractType.bind(this)}
                    />,
                  )}
                </FormItem>
              </Col>
              <Col span={6} style={{display: order.contracttype != '1' ? 'inline-block' : 'none'}}>
                <FormItem label={<span>订单协议号</span>}>
                  {getFieldDecorator('contractno', {
                    rules: [{required: order.contracttype != '1', message: '请填写订单协议号！'}],
                    initialValue: order.contractno,
                  })(<Input placeholder="填写订单协议号" disabled={disabled}/>)}
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label={<span>境外买家</span>}>
                  {getFieldDecorator('buyid', {
                    rules: [{required: true, message: '请选择境外买家！'}],
                    initialValue: order.buyid,
                  })(
                    <Select disabled={disabled}
                            style={{width: '100%'}}
                            showSearch
                            placeholder="可通过输入关键字搜索"
                            filterOption={(input, option) =>
                              option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                    >
                      {(R.isNil(buyerList) ? [] : buyerList).map(item => {
                        return (
                          <Select.Option value={item.id} key={item.id}>
                            {item.name}
                          </Select.Option>
                        );
                      })}
                    </Select>,
                  )}
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label={<span>境外收货人</span>}>
                  {getFieldDecorator('consignee', {
                    rules: [{required: true, message: '请填写境外收货人！'}],
                    initialValue: order.consignee,
                  })(<Input placeholder="填写姓名或昵称" disabled={disabled}/>)}
                </FormItem>
              </Col>
            </Row>

            <Row gutter={24}>
              <Col span={6}>
                <FormItem label={<span>报关类型</span>}>
                  {getFieldDecorator('declarationstyle', {
                    rules: [
                      {
                        required: true,
                        message: '请选择报关类型',
                      },
                    ],
                    initialValue: order.declarationstyle,
                  })(<BizParams sprCode="declarationstyle" placeholder="自营外综差别巨大，请谨慎" disabled={disabled}/>)}
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label={<span>报关方式</span>}>
                  {getFieldDecorator('declarationtype', {
                    rules: [
                      {
                        required: true,
                        message: '请选择报关方式',
                      },
                    ],
                    initialValue: order.declarationtype,
                  })(
                    <BizParams disabled={disabled}
                               sprCode="declarationtype"
                               onChange={this.handleChangeDeclarationType.bind(this)}
                    />,
                  )}
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label={<span>运输方式</span>}>
                  {getFieldDecorator('portoftransport', {
                    rules: [
                      {
                        required: true,
                        message: '请选择运输方式',
                      },
                    ],
                    initialValue: order.portoftransport,
                  })(
                    <BizParams disabled={disabled}
                               sprCode="portoftransport"
                               onChange={this.handleChangePortOfTransport.bind(this)}
                    />,
                  )}
                </FormItem>
              </Col>
              <Col
                span={6}
                style={{
                  display: (this.state.transportflag
                    ? order.declarationtype === '1' && order.portoftransport === '1'
                    : this.state.showSeaTrans)
                    ? 'inline-block'
                    : 'none',
                }}
              >
                <FormItem label={<span>装箱方式</span>}>
                  {getFieldDecorator('enchasetype', {
                    rules: [
                      {
                        required: this.state.transportflag
                          ? order.declarationtype === '1' && order.portoftransport === '1'
                          : this.state.showSeaTrans,
                        message: '请选择装箱方式',
                      },
                    ],
                    initialValue: order.enchasetype,
                  })(<BizParams sprCode="enchasetype" disabled={disabled}/>)}
                </FormItem>
              </Col>
              <Col
                span={6}
                style={{
                  display: (this.state.transportflag
                    ? order.declarationtype === '1' && order.portoftransport === '2'
                    : this.state.showRoadTrans)
                    ? 'inline-block'
                    : 'none',
                }}
              >
                <FormItem label={<span>车型</span>}>
                  {getFieldDecorator('carmodel', {
                    rules: [
                      {
                        required: this.state.transportflag
                          ? order.declarationtype === '1' && order.portoftransport === '2'
                          : this.state.showRoadTrans,
                        message: '请选择车型',
                      },
                    ],
                    initialValue: order.carmodel,
                  })(<BizParams sprCode="carmodel" disabled={disabled}/>)}
                </FormItem>
              </Col>
              <Col
                span={6}
                style={{
                  display: (this.state.transportflag
                    ? order.declarationtype === '1' && order.portoftransport === '3'
                    : this.state.showAirTrans)
                    ? 'inline-block'
                    : 'none',
                }}
              >
                <FormItem label={<span>总体积(CBM)</span>}>
                  {getFieldDecorator('totalvolume', {
                    rules: [
                      {
                        required: this.state.transportflag
                          ? order.declarationtype === '1' && order.portoftransport === '3'
                          : this.state.showAirTrans,
                        message: '请输入总体积'
                      },
                      {
                        pattern: (this.state.transportflag ? order.declarationtype === '1' && order.portoftransport === '3' : this.state.showAirTrans) ? validator.DECIMAL2.pattern : validator.NUMBER,
                        message: validator.DECIMAL2.message
                      },
                    ],
                    initialValue: order.totalvolume,
                  })(<InputNumber min={0} max={9999999999999999} style={{width: '100%'}} disabled={disabled}/>)}
                </FormItem>
              </Col>
            </Row>

            <Row gutter={24}>
              <Col span={6} style={{display: cstDecView ? 'inline-block' : 'none'}}>
                <FormItem label={<span>客户报关方式</span>}>
                  {getFieldDecorator('cstdeclarationtype', {
                    rules: [
                      {
                        required: cstDecView,
                        message: '请选择客户报关方式',
                      },
                    ],
                    initialValue: order.cstdeclarationtype,
                  })(
                    <BizParams disabled={disabled}
                               sprCode="cstdeclarationtype"
                               onChange={this.handleChangeCstDeclarationType.bind(this)}
                    />,
                  )}
                </FormItem>
              </Col>
              <Col span={6} style={{display: cstDecOneView ? 'inline-block' : 'none'}}>
                <FormItem label={<span>报关行代码</span>}>
                  {getFieldDecorator('cstdeclarationcode', {
                    rules: [
                      {
                        required: cstDecOneView,
                        message: '请输入10位报关行代码',
                      },
                    ],
                    initialValue: order.cstdeclarationcode,
                  })(<Input maxLength="10" disabled={disabled}/>)}
                </FormItem>
              </Col>
              <Col span={6} style={{display: cstDecTwoView ? 'inline-block' : 'none'}}>
                <FormItem label={<span>收件地址</span>}>
                  {getFieldDecorator('cstdeclarationaddress', {
                    rules: [
                      {
                        required: cstDecTwoView,
                        message: '请输入报关资料收件地址',
                      },
                    ],
                    initialValue: order.cstdeclarationaddress,
                  })(<Input maxLength="100" disabled={disabled}/>)}
                </FormItem>
              </Col>
              <Col span={6} style={{display: cstDecTwoView ? 'inline-block' : 'none'}}>
                <FormItem label={<span>收件人姓名</span>}>
                  {getFieldDecorator('cstreceiver', {
                    rules: [
                      {
                        required: cstDecTwoView,
                        message: '请输入收件人姓名',
                      },
                    ],
                    initialValue: order.cstreceiver,
                  })(<Input maxLength="20" disabled={disabled}/>)}
                </FormItem>
              </Col>
              <Col span={6} style={{display: cstDecTwoView ? 'inline-block' : 'none'}}>
                <FormItem label={<span>收件人电话</span>}>
                  {getFieldDecorator('cstrectelephone', {
                    rules: [
                      {
                        required: cstDecTwoView,
                        message: '请输入收件人电话',
                      },
                    ],
                    initialValue: order.cstrectelephone,
                  })(<Input maxLength="20" disabled={disabled}/>)}
                </FormItem>
              </Col>
            </Row>

            <Row gutter={24}>
              <Col span={6}>
                <FormItem label={<span>出口目的国</span>}>
                  {getFieldDecorator('countrycd', {
                    rules: [{required: true, message: '请选择出口目的国！'}],
                    initialValue: order.countrycd,
                  })(<BizParams sprCode="country" disabled={disabled}/>)}
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label={<span>贸易国地区</span>}>
                  {getFieldDecorator('tradecountry', {
                    rules: [{required: true, message: '请选择贸易国地区！'}],
                    initialValue: order.tradecountry,
                  })(<BizParams sprCode="country" disabled={disabled}/>)}
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label={<span>监管方式</span>}>
                  {getFieldDecorator('supervision', {
                    rules: [{required: true, message: '请选择监管方式！'}],
                    initialValue: order.supervision,
                  })(<BizParams sprCode="supervision" disabled={disabled}/>)}
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label={<span>征免性质</span>}>
                  {getFieldDecorator('natureexemption', {
                    rules: [{required: true, message: '请选择征免性质！'}],
                    initialValue: order.natureexemption,
                  })(<BizParams sprCode="natureExemption" disabled={disabled}/>)}
                </FormItem>
              </Col>
            </Row>

            <Row gutter={24}>
              <Col span={6}>
                <FormItem label={<span>指运港</span>}>
                  {getFieldDecorator('portofdest', {
                    rules: [{required: true, message: '请选择指运港！'}],
                    initialValue: order.portofdest,
                  })(<BizParams sprCode="portOfDest" disabled={disabled}/>)}
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label={<span>出口享惠情况</span>}>
                  {getFieldDecorator('exportbenefits', {
                    rules: [{required: true, message: '请选择出口享惠情况！'}],
                    initialValue: order.exportbenefits,
                  })(<BizParams sprCode="benefitsItem" disabled={disabled}/>)}
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label={<span>收汇方式</span>}>
                  {getFieldDecorator('settlementmethod', {
                    rules: [{required: true, message: '请选择收汇方式！'}],
                    initialValue: order.settlementmethod,
                  })(<BizParams sprCode="settlement" disabled={disabled}/>)}
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label={<span>价格条款</span>}>
                  {getFieldDecorator('priceclause', {
                    rules: [{required: true, message: '请选择价格条款！'}],
                    initialValue: order.priceclause,
                  })(
                    <BizParams disabled={disabled}
                               sprCode="priceItem"
                               onChange={this.handleChangePriceClause.bind(this)}
                    />,
                  )}
                </FormItem>
              </Col>
            </Row>

            <Row gutter={24}>
              <Col span={6} style={{display: freightView ? 'inline-block' : 'none'}}>
                <FormItem label={<span>运费</span>}>
                  {getFieldDecorator('freight', {
                    rules: [
                      {
                        required: freightView,
                        message: '请输入运费',
                        pattern: freightView ? validator.DECIMAL4.pattern : validator.NUMBER,
                        message: validator.DECIMAL4.message,
                      },
                    ],
                    initialValue: order.freight,
                  })(<InputNumber style={{width: '100%'}} min={0} max={99999999999999} disabled={disabled}/>)}
                </FormItem>
              </Col>
              <Col span={6} style={{display: freightView ? 'inline-block' : 'none'}}>
                <FormItem label={<span>运费币种</span>}>
                  {getFieldDecorator('freightcurrency', {
                    rules: [
                      {
                        required: freightView,
                        message: '请输入运费币种',
                      },
                    ],
                    initialValue: order.freightcurrency ? order.freightcurrency : undefined,
                  })(<CurrencySelect disabled={disabled}/>)}
                </FormItem>
              </Col>
              <Col span={6} style={{display: premiumView ? 'inline-block' : 'none'}}>
                <FormItem label={<span>保费</span>}>
                  {getFieldDecorator('premium', {
                    rules: [
                      {
                        required: premiumView,
                        message: '请输入保费',
                        pattern: premiumView ? validator.DECIMAL4.pattern : validator.NUMBER,
                        message: validator.DECIMAL4.message,
                      },
                    ],
                    initialValue: order.premium,
                  })(<InputNumber style={{width: '100%'}} min={0} max={99999999999999} disabled={disabled}/>)}
                </FormItem>
              </Col>
              <Col span={6} style={{display: premiumView ? 'inline-block' : 'none'}}>
                <FormItem label={<span>保费币种</span>}>
                  {getFieldDecorator('premiumcurrency', {
                    rules: [
                      {
                        required: premiumView,
                        message: '请输入保费币种',
                      },
                    ],
                    initialValue: order.premiumcurrency ? order.premiumcurrency : undefined,
                  })(<CurrencySelect disabled={disabled}/>)}
                </FormItem>
              </Col>
            </Row>

            <Row gutter={24}>
              <Col span={6}>
                <FormItem label={<span>报关币种</span>}>
                  {getFieldDecorator('currencytype', {
                    rules: [{required: true, message: '请选择报关币种！'}],
                    initialValue: order.currencytype,
                  })(<CurrencySelect disabled={disabled}/>)}
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label={<span>报关口岸</span>}>
                  {getFieldDecorator('portofentryid', {
                    rules: [{required: true, message: '请选择报关口岸！'}],
                    initialValue: order.portofentryid,
                  })(<PortSelect disabled={disabled}/>)}
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label={<span>境内货源地</span>}>
                  {getFieldDecorator('supplygoods', {
                    rules: [{required: true, message: '请选择境内货源地！'}],
                    initialValue: order.supplygoods,
                  })(
                    <Select disabled={disabled}
                            style={{width: '100%'}}
                            showSearch
                            placeholder="可通过输入关键字搜索"
                            filterOption={(input, option) =>
                              option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                    >
                      {(R.isNil(supplygoodList) ? [] : supplygoodList).map(item => {
                        return (
                          <Select.Option value={item.sprName} key={item.sprName}>
                            {item.sprValue}
                          </Select.Option>
                        );
                      })}
                    </Select>,
                  )}
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label={<span>运输方式</span>}>
                  {getFieldDecorator('transporttype', {
                    rules: [{required: true, message: '请选择运输方式！'}],
                    initialValue: order.transporttype,
                  })(<BizParams sprCode="transportType" disabled={disabled}/>)}
                </FormItem>
              </Col>
            </Row>

            <Row gutter={24}>
              <Col span={6}>
                <FormItem label={<span>包装方式</span>}>
                  {getFieldDecorator('packtype', {
                    rules: [{required: true, message: '请选择包装方式！'}],
                    initialValue: order.packtype,
                  })(<BizParams sprCode="packtype" disabled={disabled}/>)}
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label={<span>最大包装件数</span>}>
                  {getFieldDecorator('maxpacknum', {
                    rules: [{required: true, message: '请填写最大包装件数！'}],
                    initialValue: order.maxpacknum,
                  })(<InputNumber placeholder="填写最大包装件数" style={{width: '100%'}} disabled={disabled}/>)}
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label={<span>包装种类</span>}>
                  {getFieldDecorator('kindpackage', {
                    rules: [{required: true, message: '请选择包装种类！'}],
                    initialValue: order.kindpackage,
                  })(<BizParams sprCode="kindpackage" disabled={disabled}/>)}
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label={<span>实际种类</span>}>
                  {getFieldDecorator('packtypeelse', {
                    rules: [{required: false, message: '请填写实际种类！'}],
                    initialValue: order.packtypeelse,
                  })(<Input placeholder="填写实际种类" disabled={disabled}/>)}
                </FormItem>
              </Col>
            </Row>

            <Row gutter={24}>
              <Col span={6}>
                <FormItem label={<span>集装箱号</span>}>
                  {getFieldDecorator('boxno', {
                    rules: [{required: false, message: '请填写集装箱号！'}],
                    initialValue: order.boxno,
                  })(<Input placeholder="填写姓名或昵称" disabled={disabled}/>)}
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label={<span>随附单证及编号</span>}>
                  {getFieldDecorator('attachedreceiptno', {
                    rules: [{required: false, message: '请填写随附单证及编号！'}],
                    initialValue: order.attachedreceiptno,
                  })(<Input placeholder="填写统一信用代码" disabled={disabled}/>)}
                </FormItem>
              </Col>
            </Row>

            <Row gutter={24}>
              <Col span={6}>
                <FormItem label={<span>开票方式</span>}>
                  {getFieldDecorator('drawertype', {
                    rules: [
                      {
                        required: true,
                        message: '请选择开票方式',
                      },
                    ],
                    initialValue: order.drawertype,
                  })(
                    <BizParams disabled={disabled}
                               sprCode="drawertype"
                               onChange={this.handleChangeDrawerType.bind(this)}
                    />,
                  )}
                </FormItem>
              </Col>
              <Col span={6} style={{display: this.state.retrodictRate ? 'inline-block' : 'none'}}>
                <FormItem label={<span>倒推汇率</span>}>
                  {getFieldDecorator('retrodictrate', {
                    rules: this.state.retrodictRate
                      ? [
                        {
                          required: this.state.retrodictRate,
                          message: '请输入倒推汇率',
                          pattern: validator.DECIMAL4.pattern,
                          message: validator.DECIMAL4.message,
                        },
                      ]
                      : [],
                    initialValue: order.retrodictrate,
                  })(
                    <InputNumber disabled={disabled}
                                 min={0}
                                 max={99999999999999}
                                 style={{width: '100%'}}
                                 onChange={this.triggleRefreshAmt.bind(this)}
                    />,
                  )}
                </FormItem>
              </Col>
              <Col span={6} style={{display: this.state.retrodictRate ? 'inline-block' : 'none'}}>
                <FormItem label={<span>倒推费用</span>}>
                  {getFieldDecorator('retrodictfee', {
                    initialValue: order.retrodictfee ? order.retrodictfee : 0,
                  })(
                    <InputNumber disabled={disabled}
                                 min={0}
                                 max={99999999999999}
                                 style={{width: '100%'}}
                                 onChange={this.triggleRefreshAmt.bind(this)}
                    />,
                  )}
                </FormItem>
              </Col>
            </Row>

            <Row gutter={24}>
              <Col span={6}>
                <FormItem label={<span>特殊关系</span>}>
                  {getFieldDecorator('relationshipconfirm', {
                    rules: [{required: false, message: '请选择特殊关系！'}],
                    initialValue: orderTgApproval.relationshipconfirm,
                  })(
                    <RadioGroup disabled={disabled}>
                      <Radio value="1">是</Radio>
                      <Radio value="0">否</Radio>
                    </RadioGroup>,
                  )}
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label={<span>价格影响</span>}>
                  {getFieldDecorator('priceconfirm', {
                    rules: [{required: false, message: '请选择价格影响！'}],
                    initialValue: orderTgApproval.priceconfirm,
                  })(
                    <RadioGroup disabled={disabled}>
                      <Radio value="1">是</Radio>
                      <Radio value="0">否</Radio>
                    </RadioGroup>,
                  )}
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label={<span>支付特许权使用费</span>}>
                  {getFieldDecorator('paycostconfirm', {
                    rules: [{required: false, message: '请选择支付特许权使用费！'}],
                    initialValue: orderTgApproval.paycostconfirm,
                  })(
                    <RadioGroup disabled={disabled}>
                      <Radio value="1">是</Radio>
                      <Radio value="0">否</Radio>
                    </RadioGroup>,
                  )}
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label={<span>自报自缴</span>}>
                  {getFieldDecorator('selfpayconfirm', {
                    rules: [{required: false, message: '请选择自报自缴！'}],
                    initialValue: orderTgApproval.selfpayconfirm,
                  })(
                    <RadioGroup disabled={disabled}>
                      <Radio value="1">是</Radio>
                      <Radio value="0">否</Radio>
                    </RadioGroup>,
                  )}
                </FormItem>
              </Col>
            </Row>

            <Row>
              <Col>
                <Button key="forward" type="primary" disabled={disabled} onClick={() => this.handleOpenAddProduct()}>
                  添加产品
                </Button>
                <Button
                  type="primary"
                  style={{
                    marginLeft: 10,
                    display:
                      this.props.form.getFieldValue('drawertype') === '1' ? 'none' : 'inline-block',
                  }}
                  size={'default'}
                  disabled={disabled}
                  onClick={this.handleRefreshAmt.bind(this)}
                >
                  刷新价格(倒推)
                </Button>
              </Col>
            </Row>
            <Table
              rowKey={record => record.id}
              dataSource={this.state.productflag ? this.state.productList : orderProductDetails}
              columns={columns}
              size={'middle'}
              style={{marginTop: 8}}
              // scroll={{x: true}}
              pagination={false}
              scroll={{x: 2650}}

            />
            <div style={{textAlign: 'center', marginTop: 20}}>
              <span>总数量: </span>
              {R.isNil(totalnum) ? 0 : totalnum}&nbsp;&nbsp;&nbsp;&nbsp;
              <span>总净重: </span>
              <span>{R.isNil(totalweight) ? 0 : totalweight}&nbsp;kg&nbsp;&nbsp;&nbsp;&nbsp;</span>
              <span>总毛重: </span>
              <span>{R.isNil(totalgross) ? 0 : totalgross}&nbsp;kg&nbsp;&nbsp;&nbsp;&nbsp;</span>
              <span>总货值: </span>
              <span>
              {R.isNil(totleamount) ? 0 : totleamount}&nbsp;{currency}&nbsp;&nbsp;&nbsp;&nbsp;
            </span>
              <span>总包装件数: </span>
              <span>{R.isNil(totalpacknum) ? 0 : totalpacknum}</span>
            </div>

            <Row>
              <Col>
                <Button key="forward" type="primary" loading={this.props.loading}
                        style={{display: disabled ? 'none' : 'inline-block'}} onClick={() => this.getForm()}>
                  保存订单
                </Button>
                <Button
                  key="cancel"
                  style={{marginTop: 8, marginLeft: 8}}
                  onClick={() => this.handleResetFields()}
                >
                  取消
                </Button>
              </Col>
            </Row>
          </Form>
          <ChooseProduct
            wrappedComponentRef={inst => (this.formRef = inst)}
            handleAddProducts={this.handleAddProducts}
            userInfo={userInfo}
          />
        </div>
      );
    }
  },
);

function mapStateToProps(state) {
  return {
    loading: state.loading.models.orderAgent,
  };
}

export default connect(mapStateToProps)(orderForm);
